<template>
  <div class="container">
    <el-form ref="formRef" :model="formData" :rules="rules" label-width="auto">
      <el-form-item label="任务标题" prop="Title">
        <el-col :span="12">
          <el-input v-model="formData.Title" maxlength="15" :show-word-limit="true" placeholder="请输入任务标题" />
        </el-col>
      </el-form-item>
      <el-form-item label="选择企微群" prop="CustGroupList" >
        <!-- <el-form-item label="选择企微群"> -->
        <el-col>
          <ZWSelectGroup v-model="formData" :option="modelOption" show-count="never" @submit-after="handleSubmitAfter" >
            <template #radioOption>
                <el-radio :label="modelOption.allLabel">
                    <span>全部群聊</span>
                    <el-tooltip content="我是群主或管理员的全部群聊。" placement="top">
                        <el-icon class="group-tootip-icon" color="#ccc" ><QuestionFilled /></el-icon>
                    </el-tooltip>
                </el-radio>
                <el-radio :label="modelOption.selectLabel">选择群聊</el-radio>
            </template>
          </ZWSelectGroup>
          <div class="group_desc">
            <span class="grop_num_desc">
                (共选择<span class="estimated_number" >{{ estimatedNumber }}</span>个群聊)
            </span>
            <span v-if="realNumber" class="real_number">
                <el-icon color="#F56C6C" ><WarningFilled /></el-icon>
                其中{{ realNumber }}个群聊您没权限发公告，系统会自动过滤。
            </span>
          </div>
        </el-col>
      </el-form-item>
      <el-form-item label="发送方式" prop="resource">
        <el-radio-group v-model="state.SpecifySendTimeType" @change="formData.SpecifySendTime = ''">
          <el-radio :label="1">立即发送</el-radio>
          <el-radio :label="2">定时发送</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item v-if="state.SpecifySendTimeType == 2" label=" " prop="SpecifySendTime">
        <el-date-picker v-model="formData.SpecifySendTime" type="datetime" placeholder="请设置定时发送时间"
          value-format="YYYY-MM-DD HH:mm:ss" />
        <el-col>
          <div class="send_desc">到达设定时候系统自动开始群发消息</div>
        </el-col>
      </el-form-item>
      <el-form-item label="群公告" prop="Notice">
        <el-col :span="12">
          <el-input v-model="formData.Notice" type="textarea" :show-word-limit="true" maxlength="3000" :rows="8" />
        </el-col>
      </el-form-item>
      <el-form-item>
        <el-button @click="onRouteBack">取消</el-button>
        <el-button type="primary" @click="submitForm(formRef)">确定</el-button>
      </el-form-item>
    </el-form>
  </div>

</template>

<script lang="ts" setup>
import { onMounted, reactive, ref, watchEffect } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage, ElMessageBox, FormInstance, FormRules } from 'element-plus'

import ZWSelectGroup from '@renderer/components/win/ZWSelectGroup/ZWSelectGroup.vue'
import { getGroupChatNoticeDetail, putGroupChatNotice, getGroupNoticeEstimatedNumber } from '@renderer/ajax/api/publishGroupNotice'

const router = useRouter()
const route = useRoute()
const state = reactive({
  groupList: [],
  SpecifySendTimeType: 1,
  CustGroupList: []
})
const formRef = ref<FormInstance>()
const formData = reactive({
  Id: 0, // ID 不为0 为编辑
  Title: '', // 标题
  IsAllGroupChat: true,
  CustGroupList: [],
  SpecifySendTime: '', // 允许为 null， 为 null时立即发送
  Notice: ''
})
const modelOption = reactive({
  type: 'IsAllGroupChat',
  selected: 'CustGroupList',
  allLabel: true,
  selectLabel: false
})

const groupValidator = (rules, value, callback) => {
  console.log(formData);
  
  if (formData.IsAllGroupChat) {
    callback()
  } else {
    if (formData.CustGroupList.length) {
      callback()
    } else {
      callback(new Error('请选择群聊'))
    }
  }
}
const rules = reactive<FormRules>({
  Title: [{ required: true, message: '请输入任务标题', trigger: 'blur' }],
  CustGroupList: [{ required: true, validator: groupValidator, trigger: 'blur' }],
  SpecifySendTime: [{ required: true, message: '请设置立即发送时间', trigger: 'blur' }],
  Notice: [{ required: true, message: '请输入群消息', trigger: 'blur' }]
})
const onRouteBack = () => {
  router.back()
}
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate(async (valid, fields) => {
    if (valid) {

      await computedGroupNoticeEstimatedNumber()
      if (!(estimatedNumber.value - realNumber.value > 0)) {
        ElMessageBox.alert('请选择需要发公告的企微群', '提示', {
            confirmButtonText: '好的',
        })
        return
      }

      putGroupChatNotice({
        ...formData,
        CustGroupList: formData.CustGroupList.map(item => item.id)
      }).then(() => {
        const successMsg = formData.Id ? '编辑任务成功' : '新建任务成功'
        ElMessage.success(successMsg)
        onRouteBack()
      })
    } else {
      console.log('error submit!', fields)
    }
  })
}

// 数据回显
const onLook = async () => {
  const res: any = await getGroupChatNoticeDetail({Id: route.query.id})
  formData.Id = res.id
  formData.Title = res.title
  if (!res.isAllGroupChat) {
    formData.CustGroupList.splice(0, formData.CustGroupList.length, ...res.custGroupList)
  }
  formData.SpecifySendTime = res.specifySendTime
  formData.Notice = res.notice
  formData.IsAllGroupChat = !!res.isAllGroupChat
  state.CustGroupList = res.custGroupList
  state.SpecifySendTimeType = res.specifySendTime ? 2 : 1
}
onMounted(() => {
  route.query.id && onLook()
})


const handleSubmitAfter = () => {
    formRef.value.validateField(['CustGroupList'])
}
/* ----------------------------预计发布群聊数量-start---------------------------- */
/** 预计选择的群聊 */
const estimatedNumber = ref(0)
/** 无权限的群聊 */
const realNumber = ref(0)
const computedGroupNoticeEstimatedNumber = async () => {
    try {
        const params = {
            IsAllGroupChat: formData.IsAllGroupChat,
            CustGroupList: formData.CustGroupList.map(item => item.id),
        }
        const res: any = await getGroupNoticeEstimatedNumber(params)
        estimatedNumber.value = res?.num
        realNumber.value = res?.num - res?.realNum
    } catch {
        estimatedNumber.value = 0
    }
}

watchEffect(() => {
    computedGroupNoticeEstimatedNumber()
})
/* ----------------------------预计群发客户数量-end---------------------------- */
</script>
<style lang="scss" scoped>
.container {
  padding: 20px;

  .group_num_desc {
    margin-left: 10px;
    font-size: 12px;
    color: #999;
  }

  .group_list {
    display: grid;
    grid-template-columns: repeat(auto-fit, 200px);
    grid-gap: 15px;
    line-height: 1;

    .group_item {
      display: flex;
      padding: 5px;
      border: 1px solid #ebeef5;
      position: relative;

      .group_item_avatar {
        min-width: 35px;
        min-height: 35px;
        max-width: 35px;
        max-height: 35px;
        height: 35px;
        font-size: 35px;
        margin-right: 10px;
      }

      .group_item_info {
        max-width: 140px;
        display: flex;
        flex-direction: column;
        justify-content: center;

        .group_item_name {
          height: 19px;
          font-size: 14px;
          font-weight: bold;
          color: #333;
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
        }

        .group_item_desc {
          font-size: 12px;
          color: #999;
        }

        .group_item_name,
        .group_item_desc {
          white-space: nowrap;
          text-overflow: ellipsis;
          overflow: hidden;
          word-break: break-all;
        }
      }

      .group_item_del {
        position: absolute;
        right: -8px;
        top: -8px;
        font-size: 16px;
        cursor: pointer;
        color: #999;

        &:hover {
          color: #333;
        }
      }
    }
  }

  .send_desc {
    font-size: 12px;
    color: #999;
  }
}
.group_desc {
    display: flex;
    align-items: center;

}
.grop_num_desc{
    font-size: 14px;
    color: #999;
    .estimated_number {
        color: var(--el-color-primary);
    }
}

.real_number {
    margin-left: 12px;
    display: inline-flex;
    align-items: center;
    gap: 4px;
    color: #F56C6C;
}

.group-tootip-icon {
    display: inline-block;
    height: 32px;
    line-height: 32px;
    vertical-align: middle;
    margin-left: 4px;
}

</style>
